package com.liqi.frame.comm.util;


import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.util.Properties;

/**
 * 正式环境、测试环境 运行时切换控制
 * productionMode：ON 表示生产环境，否则为测试环境
 * Created by liqi on 2017/8/9.
 */
public class ConfUtil extends PropertyPlaceholderConfigurer {
    private static boolean productionMode=false;
//    private static Logger logger = LoggerFactory.getLogger(ConfUtil.class);
    private static final Log log = LogFactory.get();
    private static String testPrifix="test.";
    private static Properties propsRef=new Properties();
    public ConfUtil(){
//        log.info("==========ConfUtil init=========");
    }
    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
        propsRef=props;
        String runMode=propsRef.getProperty("productionMode");
        if("ON".equalsIgnoreCase(runMode) ||"1".equalsIgnoreCase(runMode)){
            productionMode=true;
            logger.warn("==ServerRunMode:Production Server==");
        }else{
            logger.warn("==ServerRunMode:TestServer==");
        }

        super.processProperties(beanFactoryToProcess, props);
    }
    @Override
    protected String resolvePlaceholder(String placeholder, Properties props) {
        if(!productionMode){
            String testValue=props.getProperty(testPrifix+placeholder);
            if(testValue != null && !"".equals(testValue)){
                return testValue;
            }
        }
        return props.getProperty(placeholder);
    }

    public static String getConf(String name, String defaulValue) {
        if(!productionMode){
            String testValue = propsRef.getProperty(testPrifix+name);
            if (testValue != null && !"".equals(testValue)) {
                return testValue;
            }
        }
        return propsRef.getProperty(name,defaulValue);
    }

    public static String getConf(String name) {
        return getConf(name, null);
    }
    private static boolean isProductionMode() {
        return productionMode;
    }
}
